package cn.gson.crm.model.service;

import cn.gson.crm.model.dao.*;
import cn.gson.crm.model.mapper.CenterMapper;
import cn.gson.crm.model.mapper.SalesMapper;
import cn.gson.crm.model.pojos.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class SalesService {

    @Autowired
    SalesMapper salesMapper;

    @Autowired
    SalesDao salesDao;

    @Autowired
    SolutionDao solutionDao;

    @Autowired
    CompetitorDao competitorDao;

    @Autowired
    CartDao cartDao;

    @Autowired
    OfferDao offerDao;

    @Autowired
    OfferDetailDao offerDetailDao;

    @Autowired
    FollowDao followDao;

    @Autowired
    CheckDao checkDao;

    @Autowired
    CenterMapper centerMapper;

    public List<ProductXq> productSelect1(){
        return salesMapper.productSelect1();
    }

    //sales:查询购物车产品
    public List<Cart> selectCart(int salesId){
        return salesMapper.selectCart(salesId);
    }

    //sales:删除销售机会
    public String deleteSales(int salesId){
        String result;
        Sales sales = salesDao.findById((long)salesId).get();
        Contract contract = sales.getContract();
        if(contract!=null){
            result="此销售机会下面有合同，不能删除";
        }else{
            result="成功";
            sales.setSalesPlan("0");
            salesDao.save(sales);
        }
        return result;
    }

    //sales:新增销售机会
    public void addSales(String position){
        JSONObject object = (JSONObject)JSONObject.parse(position);
        List list = object.getObject("cart",List.class);
        JSONArray array = (JSONArray) JSONArray.parseArray(String.valueOf(list));
        Sales sales = object.getObject("sales",Sales.class);
        sales.setSalesPlan("1");
        salesDao.save(sales);
        JSONObject jsonObject =null;
        for (int i = 0; i < array.size(); i++) {
            jsonObject = (JSONObject)array.get(i);
            Cart cart = new Cart();
            cart.setSales(sales);
            cart.setCartNum(Long.parseLong(jsonObject.getString("cartNum")));
            cart.setCartColor(jsonObject.getString("cartColor"));
            cart.setCartSize(jsonObject.getString("cartSize"));
            cart.setCartUnit(jsonObject.getString("cartUnit"));
            cart.setCartName(jsonObject.getString("cartName"));
            cart.setCartKcnum(Integer.parseInt(jsonObject.getString("cartKcnum")));
            cart.setCartPrice(Double.parseDouble(jsonObject.getString("cartPrice")));
            if(!jsonObject.getString("cartId").equals("")){
                cart.setCartId(Long.parseLong(jsonObject.getString("cartId")));
            }
            cartDao.save(cart);
        }
    }



    //查询销售机会
    public List<Sales> selectSales(Integer ygId,int salesId,String salesTheme,String salesStage){
        List<Sales> sales = salesMapper.selectSales(ygId,salesId, salesTheme, salesStage);
        for (int i = 0; i < sales.size(); i++) {
            Contract contract = sales.get(i).getContract();
            if(contract!=null && sales.get(i).getSalesPoss()!=100){
                sales.get(i).setSalesPoss((long)100);
                sales.get(i).setSalesStage("合同签约");
                salesDao.save(sales.get(i));
            }
        }
        return sales;
    }

    //sales:查询产品
    public List<Stock> productSelect(long categoryId,String name){
        return salesMapper.productSelect(categoryId,name);
    }

    //客户需求修改
    public void khxqUpdate(String salesId,String salesDemand,String salesRemark){
        Sales sales = salesDao.findById(Long.parseLong(salesId)).get();
        sales.setSalesStage("需求分析");
        sales.setSalesPoss((long)40);
        sales.setSalesDemand(salesDemand);
        sales.setSalesRemark(salesRemark);
        salesDao.save(sales);
    }

    //option:solution:查询解决方案
    public List<Solution> selectSolution(int salesId){
        return salesMapper.selectSolution(salesId);
    }

    //option:solution:新增修改解决方案
    public void addSolution(Solution solution){
        //修改销售机会进度
        List<Solution> solutions = salesMapper.selectSolution((int) solution.getSalesBySalesId().getSalesId());
        Sales sales = salesDao.findById(solution.getSalesBySalesId().getSalesId()).get();
        if(solutions.size()<=0 && sales.getSalesPoss()<=80){
            sales.setSalesPoss((long)80);
            sales.setSalesStage("方案制定");
            salesDao.save(sales);
        }
        solutionDao.save(solution);
    }

    //option:solution:删除解决方案
    public void updateSolution(String solutionState,int solutionId){
        salesMapper.updateSolution(solutionState,solutionId);
        Solution solution = solutionDao.findById((long) solutionId).get();
        List<Solution> solutions = salesMapper.selectSolution((int) solution.getSalesBySalesId().getSalesId());
        List<Offer> offers = salesMapper.selectOffer((int) solution.getSalesBySalesId().getSalesId());
        List<Competitor> competitors = salesMapper.selectCompetitor((int) solution.getSalesBySalesId().getSalesId(), "");
        Sales sales = salesDao.findById(solution.getSalesBySalesId().getSalesId()).get();
        //如果此销售机会没有解决方案，进度减少
        //报价为空时
        if(offers.size()<=0){
            if(solutions.size()<=0){
                if(competitors.size()<=0){
                    if(sales.getSalesDemand().equals("") && sales.getSalesRemark().equals("")){
                        sales.setSalesPoss((long)20);
                        sales.setSalesStage("立项评估");
                        salesDao.save(sales);
                    }else{
                        sales.setSalesPoss((long)40);
                        sales.setSalesStage("需求分析");
                        salesDao.save(sales);
                    }
                }else{
                    sales.setSalesPoss((long)60);
                    sales.setSalesStage("招投标/竞争");
                    salesDao.save(sales);
                }
            }
        }
    }

    //competitor:查询竞争对手
    public List<Competitor> selectCompetitor(int salesId,String compeCompany){
        return salesMapper.selectCompetitor(salesId,compeCompany);
    }

    //competitor:删除竞争对手
    public void updateCompetitor(int compeId){
        Competitor competitor = competitorDao.findById((long) compeId).get();
        competitor.setCompeState("0");
        competitorDao.save(competitor);
        List<Solution> solutions = salesMapper.selectSolution((int)competitor.getSales().getSalesId());
        List<Offer> offers = salesMapper.selectOffer((int)competitor.getSales().getSalesId());
        List<Competitor> competitors = salesMapper.selectCompetitor((int)competitor.getSales().getSalesId(), "");
        Sales sales = salesDao.findById(competitor.getSales().getSalesId()).get();
        //如果此销售机会没有解决方案，进度减少
        //报价为空时
        if(offers.size()<=0){
            if(solutions.size()<=0){
                if(competitors.size()<=0){
                    if(sales.getSalesDemand().equals("") && sales.getSalesRemark().equals("")){
                        sales.setSalesPoss((long)20);
                        sales.setSalesStage("立项评估");
                        salesDao.save(sales);
                    }else{
                        sales.setSalesPoss((long)40);
                        sales.setSalesStage("需求分析");
                        salesDao.save(sales);
                    }
                }else{
                    sales.setSalesPoss((long)60);
                    sales.setSalesStage("招投标/竞争");
                    salesDao.save(sales);
                }
            }
        }
    }

    //competitor:新增修改竞争对手
    public void addCompetitor(Competitor competitor){
        List<Competitor> competitors = salesMapper.selectCompetitor((int)competitor.getSales().getSalesId(),"");
        Sales sales = salesDao.findById(competitor.getSales().getSalesId()).get();
        if(competitors.size()<=0){
            sales.setSalesPoss((long)60);
            sales.setSalesStage("招投标/竞争");
            salesDao.save(sales);
        }
        competitorDao.save(competitor);
    }

    //offer:新增修改报价
    public void addOffer(String position,long ygId){
        JSONObject object = (JSONObject)JSONObject.parse(position);
        List list = object.getObject("offerDetail",List.class);
        JSONArray array = (JSONArray) JSONArray.parseArray(String.valueOf(list));
        Offer offer = object.getObject("offer",Offer.class);
        System.err.println("李莹莹"+offer.getSales().getSalesTheme());
        //如果此销售机会之前没有报价，此时新增要修改销售机会的进度
        List<Offer> offers = salesMapper.selectOffer((int) offer.getSales().getSalesId());
        Sales sales = salesDao.findById(offer.getSales().getSalesId()).get();
        if(offers.size()<=0){
            sales.setSalesPoss((long)90);
            sales.setSalesStage("商务谈判");
            salesDao.save(sales);
        }
        long id=offer.getOfferId();
        if(offer.getOfferId()==0){
            //新增时如果有未审核的，把未审核改为已作废，把审核表的数据删除
            for (int i = 0; i < offers.size(); i++) {
                if(offers.get(i).getOfferAudit().equals("未审核")){
                    Check check =salesMapper.selectCheck((int) offer.getOfferId());
                    //删除审核表数据
                    checkDao.deleteByCheckId(check.getCheckId());
                    offers.get(i).setOfferAudit("已作废");
                    offers.get(i).setSales(offers.get(i).getSales());
                    offerDao.save(offers.get(i));
                }
            }
        }
        offerDao.save(offer);
        if(id==0){
            //新增审核表
            Check check=new Check();
            check.setChecksqinName(ygId);
            check.setCheckName(offer.getEmployee().getYgId());
            check.setCheckType("报价审批");
            check.setChecktypeid((int)offer.getOfferId());
            check.setCheckDate(offer.getOfferDate());
            check.setCheckCondition("未审核");
            checkDao.save(check);
        }
        JSONObject jsonObject =null;
        for (int i = 0; i < array.size(); i++) {
            jsonObject = (JSONObject)array.get(i);
            OfferDetail offerDetail = new OfferDetail();
            offerDetail.setOfferByOfferId(offer);
            Cart cart = cartDao.findById(Long.parseLong(jsonObject.getString("cartByCartId"))).get();
            offerDetail.setCartByCartId(cart);
            System.err.println("1id:"+jsonObject.getString("proId"));
            if(!jsonObject.getString("proId").equals("")){
                offerDetail.setProId(Long.parseLong(jsonObject.getString("proId")));
            }
            System.out.println("2id:"+offerDetail.getProId());
            offerDetail.setProDiscount(jsonObject.getString("proDiscount"));
            offerDetail.setProMoney(Double.parseDouble(jsonObject.getString("proMoney")));
            offerDetail.setProPrice(Double.parseDouble(jsonObject.getString("proPrice")));
            offerDetailDao.save(offerDetail);
        }
    }

    //offer:查询报价，报价详单，购物车
    public List<Offer> selectOffer(int salesId){
        return salesMapper.selectOffer(salesId);
    }

    //offer:删除报价
    public void updateOffer(int offerId){
        Offer offer = offerDao.findById((long) offerId).get();
        offer.setOfferState("0");
        offerDao.save(offer);
        Check check = salesMapper.selectCheck((int) offer.getOfferId());
        //删除审核表数据
        checkDao.deleteByCheckId(check.getCheckId());
        List<Solution> solutions = salesMapper.selectSolution((int)offer.getSales().getSalesId());
        List<Offer> offers = salesMapper.selectOffer((int)offer.getSales().getSalesId());
        List<Competitor> competitors = salesMapper.selectCompetitor((int)offer.getSales().getSalesId(), "");
        Sales sales = salesDao.findById(offer.getSales().getSalesId()).get();
        //如果此销售机会没有解决方案，进度减少
        //报价为空时
        if(offers.size()<=0){
            if(solutions.size()<=0){
                if(competitors.size()<=0){
                    if(sales.getSalesDemand().equals("") && sales.getSalesRemark().equals("")){
                        sales.setSalesPoss((long)20);
                        sales.setSalesStage("立项评估");
                        salesDao.save(sales);
                    }else{
                        sales.setSalesPoss((long)40);
                        sales.setSalesStage("需求分析");
                        salesDao.save(sales);
                    }
                }else{
                    sales.setSalesPoss((long)60);
                    sales.setSalesStage("招投标/竞争");
                    salesDao.save(sales);
                }
            }else{
                sales.setSalesPoss((long)80);
                sales.setSalesStage("方案制定");
                salesDao.save(sales);
            }
        }
    }

    //funnel:漏斗图
    public Map<String,Object> create(String leader, int ygId){
        Map<String,Object> map = new HashMap<>();
        if(ygId==0){
            JSONObject object = (JSONObject) JSONObject.parse(leader);
            JSONObject jsonObject =null;
            List list = object.getObject("leader",List.class);
            List<Sales> all = new ArrayList();
            if(list.size()==0){
                all=salesMapper.create(0);
            }else{
                JSONArray array = (JSONArray) JSONArray.parseArray(String.valueOf(list));
                Employee emp = null;
                for(int i=0;i<array.size();i++){
                    jsonObject = (JSONObject)array.get(i);
                    emp = new Employee();
                    emp.setYgId(Integer.parseInt(jsonObject.getString("ygId")));
                    emp.setYname(jsonObject.getString("yname"));
                    List<Sales> sales = new ArrayList();
                    sales = salesMapper.create((int)emp.getYgId());
                    for (int j = 0; j < sales.size(); j++) {
                        all.add(sales.get(j));
                    }
                }
            }
            map.put("funnel",all);
            map.put("ygId",ygId);
        }else{
            List<Sales> all=salesMapper.create(ygId);
            map.put("funnel",all);
            map.put("ygId",1);
        }
        return map;
    }

    //option:follow:新增修改
    public void addFollow(Follow follow){
        follow.setFollowStage("1");
        followDao.save(follow);
    }

    //option:follow:查询跟进记录
    public List<Follow> selectFollow(int salesId){
        return salesMapper.selectFollow(salesId);
    }

    //option:follow:删除跟进记录
    public void deleteFollow(int followId){
        Follow follow = followDao.findById((long) followId).get();
        follow.setFollowStage("0");
        followDao.save(follow);
    }

    //print：报价查询
    public List<Offer> printOffer(int offerId){
        return salesMapper.printOffer(offerId);
    };

    //print：报价详情查询
    public List<OfferDetail> offerDetailPrint( int offerId){
        return  salesMapper.offerDetailPrint(offerId);
    };
    //统计商机
    public List<Shuliang> selectsales(){
        System.out.println(salesMapper.selectsales());
        return salesMapper.selectsales();
    }

    //查询主页销售漏斗
    public Map<String,Object> select1(){
        List<Sales> list =salesMapper.select1();
        Map<String,Object> map=new HashMap<>();
        List<String> aa=new ArrayList<>();//类型
        List<Integer> bb=new ArrayList<>();//数量
        for(int i=0;i<list.size();i++){
            aa.add(list.get(i).getSalesStage());
            bb.add(salesDao.select1(list.get(i).getSalesStage()));
        }
        map.put("aa",aa);
        map.put("bb",bb);
        return map;
    }
    public Map<String,Object> select2(){
        List<Sales> list =salesMapper.select1();
        Map<String,Object> map=new HashMap<>();
        List<String> aa=new ArrayList<>();//类型
        List<Integer> bb=new ArrayList<>();//数量
        for(int i=0;i<list.size();i++){
            aa.add(list.get(i).getSalesStage());
            bb.add(salesDao.select2(list.get(i).getSalesStage()));

        }
        map.put("aa",aa);
        map.put("bb",bb);
        return map;
    }

}
